import React from 'react';
import { Row, Col, Button, message, Form, Popconfirm, Upload, Icon, Table} from 'antd';
const R = require('ramda');
import BizParams from '../../../components/commons/BizParams';
import SingleUpload from '../../../components/commons/SingleUpload';
import ChooseProduct from '../components/ChooseProduct';
import dateFormat from 'dateformat';
import {download} from '../../../utils/commons'

const FormItem = Form.Item;
export default Form.create({wrappedComponentRef: true})(class ConfirmLetter extends React.Component {
	constructor(props) {
        super(props);
        this.init(props.dataSource, true);
	}

     componentWillReceiveProps(nextProps) {
        this.init(nextProps.dataSource);
    } 

    init = (dataSource, flag) =>{
        dataSource = R.isNil(dataSource) ? {} : dataSource;
        let productList = R.isEmpty(dataSource) || R.isNil(dataSource.orderProducts) ? [] : dataSource.orderProducts;
        if(flag) this.state = {dataSource: dataSource, productList: productList}
        else this.setState({dataSource: dataSource, productList: productList});
    }

    handleResetFields = () => {
        if(this.refs.confirmLettterUpload)this.refs.confirmLettterUpload.resetUpload();
		this.props.form.resetFields();
	}

    handleExportConfirmLetter = () => {
        let url =  apiPath.imagent + "/api/exportLetter";
        let conditions = {orderId: R.isNil(this.state.dataSource.id) ? "" : this.state.dataSource.id, filename: '进口服务订单确认函_V1.0.ftl'};
        download(url, conditions);
    }

    handleEndOrder = () => {
        let orderId = R.isNil(this.state.dataSource.id) ? "" : this.state.dataSource.id;
        this.props.dispatch({
            type: 'orderManage/cancelOrderById',
            payload: {
                id : orderId,
                searchConditions: this.props.searchConditions
            }
        });
        if(this.props.handleCancel){
            this.props.handleCancel();
        }
    }

    handleConfirmLetter = () => {
        if(R.isNil(this.refs.confirmLettterUpload.getUrl()) || R.isEmpty(this.refs.confirmLettterUpload.getUrl())){
            message.error("请先上传确认函!");
            return;
        }
        let orderId = R.isNil(this.state.dataSource.id) ? "" : this.state.dataSource.id;
        this.props.dispatch({
            type: 'orderManage/confirmLetterById',
            payload: {
                id : orderId,
                url: this.refs.confirmLettterUpload.getUrl(),
                searchConditions: this.props.searchConditions
            }
        });
        if(this.props.handleCancel){
            this.props.handleCancel(["5"]);
        }
    }

    renderContent = (value, row, index) => {
        const obj = {
          children: value,
          props: {},
        };
        if (index === 0) {
          obj.props.colSpan = 0;
        }
        return obj;
      };

    columns = [
        {title: '服务项目', dataIndex: 'serviceItem', key: 'serviceItem',
              render: (value, row, index) => {
                const obj = {
                    children: value,
                    props: {},
                };
                if (index === 1) {
                    obj.props.rowSpan = 6;
                }else if(index === 7){
                    obj.props.rowSpan = this.state.productList.length + 1;
                }else if(index === 8 + this.state.productList.length){
                    obj.props.rowSpan = 2;
                }else if(index === 0 || index > 9 + this.state.productList.length){
                    obj.props.rowSpan = 1;
                }else{
                    obj.props.rowSpan = 0;
                }
                return obj; 
            }, 
        },
        {title: '商品名称', dataIndex: 'productname', key: 'productname',
        render: (text, row, index) => {
            if (index !== 0) {
              return text;
            }else{
                return {
                  children: text,
                  props: {
                    colSpan: 4,
                  },
                };
            }
        }},
        {title: 'HScode', dataIndex: 'producthscode', key: 'producthscode', render: this.renderContent},
        {title: '退税率(%)', dataIndex: 'taxrate', key: 'taxrate', render: this.renderContent},
        {title: '监管条件', dataIndex: 'supercondition', key: 'supercondition', render: this.renderContent},
    ]


	render() {
        let supplyGoods = "";
		let dataSource = R.isNil(this.props.dataSource) ? {} : this.props.dataSource;

        let tempProductList = [];
        R.map((row) => {
            let product = {};
            product.productname = row.name;
            product.producthscode = row.hscode;
            product.taxrate = row.taxrate;
            product.supercondition = row.superCondition;
            supplyGoods = row.domesticDestinationValue;

            tempProductList = R.concat(tempProductList, [product]);
        }, this.state.productList)
        //报关抬头0自己 1客户(双抬头)
        let provider = this.state.dataSource.declarationstyle === "0" ? this.props.lesseeInfo.lesseeNameCn : this.props.customer.companyname;

        let tableDataSourceAbove = [
            {serviceItem: '服务项目', productname: '货物进口信息', producthscode: '', taxrate: '', supercondition: ''},
            {serviceItem: '通关', productname: '境内收货人', producthscode: this.props.lesseeInfo.lesseeNameCn,
            taxrate: '消费使用单位', supercondition: provider},

            {serviceItem: '', productname: '进境关别', producthscode: R.isNil(this.props.placeClearance) || R.isNil(this.props.placeClearance.placeName) ? "" : this.props.placeClearance.placeName, taxrate: '启运国', supercondition: R.isNil(this.props.countryCD) || R.isNil(this.props.countryCD.sprValue) ? "" : this.props.countryCD.sprValue},
            {serviceItem: '', productname: '贸易国(地区)', producthscode: R.isNil(this.props.tradeCountry) || R.isNil(this.props.tradeCountry.sprValue) ? "" : this.props.tradeCountry.sprValue, taxrate: '', supercondition: ''},
            {serviceItem: '', productname: '报关总价', producthscode: R.isNil(this.state.dataSource.totalamount) ? 0 : this.state.dataSource.totalamount, taxrate: '境内目的地', supercondition: supplyGoods},
            {serviceItem: '', productname: '总毛重', producthscode: (R.isNil(this.state.dataSource.totalgross) ? 0 : this.state.dataSource.totalgross) + "  kg", taxrate: '总净重', supercondition: (R.isNil(this.state.dataSource.totalweight) ? 0 : this.state.dataSource.totalweight) + "  kg"},
            {serviceItem: '', productname: '总件数', producthscode: R.isNil(this.state.dataSource.totalpacknum) ? 0 : this.state.dataSource.totalpacknum, taxrate: '包装种类', supercondition: R.isNil(this.props.kindPackage) || R.isNil(this.props.kindPackage) ? "" : this.props.kindPackage},
            {serviceItem: '产品', productname: '商品名称', producthscode: "HScode", taxrate: '关税(%)', supercondition: '监管条件'},
        ];

        tableDataSourceAbove = R.concat(tableDataSourceAbove, tempProductList);

        let key = 1;
        let tableDataSourceAboveWithKey = tableDataSourceAbove.map((product)=> {
            product.key = key++;
            return product;
        });
        
        let key1 = 1;
        let costList = [];
        R.map((row) => {
            let cost = R.pick(['chargeTypeName', 'costToCNY'])(row);
            cost.costRule = '';
            cost.key = key1++;
            costList.push(cost);
        }, this.props.orderCharges);

		return (
            <div>
                <div style={{display: 'flex', marginLeft: 40}}>
                    <span style={{width: 145}}>
                        <SingleUpload url={dataSource.outputservice} disabled={this.props.disabled} text="上传订单确认函" ref="confirmLettterUpload" dataSource={dataSource}/>
                    </span>
                    <Button style={{marginLeft: 80}} type="primary" key="export" size="large" icon="export" onClick={this.handleExportConfirmLetter.bind(this)} disabled={this.props.disabled}>导出确认函</Button>
                    <Popconfirm onConfirm={this.handleEndOrder.bind(this)} okText="是" cancelText="否"
                        placement="leftTop" title={'订单终止后将不可以恢复，是否继续终止订单?'}>
                        <Button style={{marginLeft: 80}} type="primary" key="end" size="large" icon="close" disabled={this.props.disabled}>终止订单</Button>
                    </Popconfirm>
                    <Button style={{marginLeft: 80}} type="primary" key="confirm" size="large" icon="check" onClick={this.handleConfirmLetter.bind(this)} disabled={this.props.disabled}>确认收函</Button>
                </div>
                <div className="ant-menu-item-divider" style={{marginTop: 19}}/>
                <div style={{textAlign: 'center', marginTop: 30}}>
                    <span><b><font size="4">进口服务订单确认函</font></b></span>
                    <span style={{textAlign: 'left', lineHeight: 2}}><p>至{R.isNil(this.props.lesseeInfo.lesseeNameCn) ? "" : this.props.lesseeInfo.lesseeNameCn}:</p></span>
                    <span style={{textAlign: 'left', lineHeight: 2}}><p>我方对以下委托贵司进口的服务项目及相关项目明细信息了解并认可:同意本确认函出具后,需待贵司确认接受委托后双方的委托服务关系方成立.</p></span>
                    <span style={{textAlign: 'left', lineHeight: 2}}><p>我方就委托贵司办理的产品进口服务及货物相关信息确认如下:</p></span>
                    <span style={{textAlign: 'left', lineHeight: 2}}><p>一:服务项目及货物进口信息:</p></span>
                </div>
                <Table showHeader={false} pagination={false} bordered={true} columns={this.columns} size={'small'} style={{marginTop: 0}} dataSource={tableDataSourceAboveWithKey} width="80%"/>
                <div style={{marginTop: 10}}>
                    <span style={{lineHeight: 2}}><p>我方确认上述进口货物及信息准确真实、合法有效,如因上述信息错误导致的一切费用、损失及责任均由我方承担.我方承诺上述货物已与海外买家</p></span>
                    <span style={{lineHeight: 2}}><p>签订相关的贸易合同并与海外买家约定由贵司代为进口及代为收汇.</p></span>
                    {/* <span style={{lineHeight: 3}}><p>二:预计费用清单:(以下为预计费用,实际费用实报实销)</p></span> */}
                </div>
                {/* <Table pagination={false} bordered={true} columns={this.columns2} size={'small'} style={{marginTop: 0}} width="80%" dataSource={costList}/> */}
                <div style={{marginTop: 10}}>
                    {/* <span style={{lineHeight: 2}}><p>我方知悉上述费用清单为预估费用,同意此进口服务订单的费用结算以实际产生的为准。</p></span> */}
                    <span style={{lineHeight: 2}}><p>委托单位: {R.isNil(this.props.customer) || R.isNil(this.props.customer.companyname) ? "" : this.props.customer.companyname}</p></span>
                    <span style={{lineHeight: 3}}><p>时间: {dataSource.confirmLetterTime ? dateFormat(dataSource.confirmLetterTime, 'yyyy年mm月dd日') : dateFormat(new Date(), 'yyyy年mm月dd日')}</p></span>
                </div>
            </div>
		)
	}
})